package cn.njyd.corejava.socket.day01;

/**
 * ClassName:ChatClient
 * Package:cn.njyd.corejava.socket.day01
 * Description:
 *
 * @Date:2025/8/15 15:24
 * @Author:lixiaoming-李晓明
 */
import java.io.*;
import java.net.*;
import java.util.Scanner;

public class ChatClient {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        try {
            System.out.println("请输入服务器IP地址 (默认本地):");
            String host = scanner.nextLine();
            if (host.isEmpty()) {
                host = "localhost";
            }

            System.out.println("请输入服务器端口 (默认12345):");
            String portStr = scanner.nextLine();
            int port = portStr.isEmpty() ? 12345 : Integer.parseInt(portStr);

            Socket socket = new Socket(host, port);
            System.out.println("已连接到聊天服务器");

            // 启动线程接收服务器消息
            new Thread(new MessageReceiver(socket)).start();

            // 主线程发送消息到服务器
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));

            String message;
            while ((message = consoleReader.readLine()) !=null) {
                out.println(message);
                if ("exit".equalsIgnoreCase(message)) {
                    break;
                }
            }

            socket.close();
            System.out.println("已断开与服务器的连接");
        } catch (IOException e) {
            System.err.println("客户端异常: " + e.getMessage());
        } finally {
            scanner.close();
        }
    }

    private static class MessageReceiver implements Runnable {
        private final Socket socket;

        public MessageReceiver(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String message;
                while ((message = in.readLine()) !=null) {
                    System.out.println(message);
                }
            } catch (IOException e) {
                System.out.println("与服务器的连接已断开");
            }
        }
    }
}